//
//  PlSOnSiteLoader.m
//  Injector
//
//  Created by ∞ on 30/11/07.
//  Copyright 2007 Emanuele Vulcano. All rights reserved.
//

#import "PlSOnSiteLoader.h"
#import "PlSSIMBLManager.h"
#import "PlSPlugIn.h"
#import "PlSAppSpecifier.h"
#import "PlSInputManagerManager.h"
#import "PlSCFPreferences.h"

#import <Carbon/Carbon.h>

@implementation PlSOnSiteLoader

//+ (id) sharedInstance {
//	static id myself = nil; if (!myself)
//		myself = [self new];
//	
//	NSLog(@"myself = %@", myself);
//	return myself;
//}

+ (void) install {
	NSAutoreleasePool* pool = [NSAutoreleasePool new];
	
	PlSSIMBLManager* mgrSIMBL = [[[PlSSIMBLManager alloc] init] autorelease];
	PlSInputManagerManager* mgrIM = [[[PlSInputManagerManager alloc] init] autorelease];

	PlSCFPreferences* prefs = [[[PlSCFPreferences alloc] init] autorelease];
	mgrSIMBL.preferencesController = prefs;
	mgrIM.preferencesController = prefs;
	
	[mgrSIMBL rescan];
	[mgrIM rescan];
	
	NSMutableArray* arr = [NSMutableArray array];
	[arr addObjectsFromArray:mgrSIMBL.plugIns];
	[arr addObjectsFromArray:mgrIM.plugIns];
	
	for (PlSPlugIn* pin in arr) {
		if (!pin.isManaged || !pin.isLoadable) continue;
		
		if (pin.canCheckQuarantineOnUserVisiblePath &&
			[pin.userVisiblePath hasPrefix:NSHomeDirectory()]) {
			NSURL* url = [NSURL fileURLWithPath:pin.userVisiblePath];
			FSRef ref;
			CFURLGetFSRef((CFURLRef) url, &ref);
			
			NSDictionary* attrs = nil;
			if (LSCopyItemAttribute(&ref, kLSRolesAll, kLSItemQuarantineProperties, (CFTypeRef*) &attrs) == noErr) {
				[attrs release];
				L0Log(@"plug-in %@ is quarantined inside home folder -- discarded.", pin.identifier);
				continue; // we don't load quarantined plug-ins in the home folder.
			}
		}
		
		L0Log(@"%@", pin.identifier);
		if ([PlSAppSpecifier anySpecifier:pin.appSpecifiers isCompatibleWithApplication:[NSBundle mainBundle]]) {
			L0Log(@"(%@ seems to be compatible, loading.)", pin.identifier);
			
			BOOL loaded = [pin loadNow];
			L0Log(@"Attempted to load %@, result = %d (1 means success).", pin.identifier, loaded);
		}
	}
	
	[pool release];
}

@end
